import axios from "axios";
import config from '../config'
import useToken from "../store/token";
import notification from "./notification";

//获取请求的路径
const baseURL = config.baseURL

//创建实例
const service = axios.create({ baseURL })

//在请求中上加请求头， 带token
service.interceptors.request.use(config => {
    const { token } = useToken()
    if (token) {
        config.headers.jwt = token
    }
    return config

})

//响应的统一处理
service.interceptors.response.use(response => {
    const { errno, data, errmsg } = response.data
    if (errno === 0) {
        if (errmsg !== '') {
            notification({
                message: errmsg,
                type: 'success'
            })

        }
        return data || true
    }
    notification({
        message: errmsg,
        type: 'error'
    })
    if (errno === 2) {
        router.push({ name: 'login' })
    }
    return false;
}, error => {
    notification({
        message: '请求失败',
        type: 'error'
    })
    console.log(error)
})
export default service